package com.mmc.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mmc.entity.Message;
import com.mmc.entity.User;
import com.mmc.mapper.MessageMapper;
import com.mmc.mapper.UserMapper;
import com.mmc.service.MessageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 消息服务实现类
 *
 * @author kunfe
 * @since 2024-01-01
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

    private final MessageMapper messageMapper;
    private final UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendMessage(Message message) {
        // 设置发送者信息
        Long senderId = StpUtil.getLoginIdAsLong();
        User sender = userMapper.selectById(senderId);
        if (sender != null) {
            message.setSenderId(senderId);
            message.setSenderName(sender.getRealName());
        }

        // 设置接收者信息
        User receiver = userMapper.selectById(message.getReceiverId());
        if (receiver != null) {
            message.setReceiverName(receiver.getRealName());
        }

        // 设置默认状态
        message.setStatus(0); // 未读
        message.setIsTop(0);  // 不置顶
        if (message.getPriority() == null) {
            message.setPriority(2); // 默认中等优先级
        }

        return save(message);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSendMessage(List<Long> receiverIds, String title, String content, Integer type) {
        if (CollUtil.isEmpty(receiverIds)) {
            return false;
        }

        Long senderId = StpUtil.getLoginIdAsLong();
        User sender = userMapper.selectById(senderId);
        String senderName = sender != null ? sender.getRealName() : "系统";

        List<Message> messages = receiverIds.stream().map(receiverId -> {
            User receiver = userMapper.selectById(receiverId);
            Message message = new Message();
            message.setType(type);
            message.setTitle(title);
            message.setContent(content);
            message.setSenderId(senderId);
            message.setSenderName(senderName);
            message.setReceiverId(receiverId);
            message.setReceiverName(receiver != null ? receiver.getRealName() : "");
            message.setStatus(0);
            message.setIsTop(0);
            message.setPriority(2);
            return message;
        }).toList();

        return saveBatch(messages);
    }

    @Override
    public Page<Message> getMessagePage(Page<Message> page, Long receiverId, Integer type, Integer status) {
        return messageMapper.selectPageByReceiverId(page, receiverId, type, status);
    }

    @Override
    public Long getUnreadCount(Long receiverId) {
        return messageMapper.countUnreadByReceiverId(receiverId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean markAsRead(Long messageId, Long receiverId) {
        Message message = getById(messageId);
        if (message != null && message.getReceiverId().equals(receiverId)) {
            message.setStatus(1);
            message.setReadTime(LocalDateTime.now());
            return updateById(message);
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchMarkAsRead(List<Long> messageIds, Long receiverId) {
        if (CollUtil.isEmpty(messageIds)) {
            return false;
        }
        return messageMapper.batchMarkAsRead(messageIds, receiverId) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteMessage(Long messageId, Long receiverId) {
        Message message = getById(messageId);
        if (message != null && message.getReceiverId().equals(receiverId)) {
            return removeById(messageId);
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteMessage(List<Long> messageIds, Long receiverId) {
        if (CollUtil.isEmpty(messageIds)) {
            return false;
        }
        
        // 只删除属于当前用户的消息
        List<Message> messages = listByIds(messageIds);
        List<Long> validIds = messages.stream()
                .filter(msg -> msg.getReceiverId().equals(receiverId))
                .map(Message::getId)
                .toList();
        
        return CollUtil.isNotEmpty(validIds) && removeByIds(validIds);
    }

    @Override
    public List<Message> getLatestMessages(Long receiverId, Integer limit) {
        return messageMapper.selectLatestMessages(receiverId, limit != null ? limit : 10);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean markAllAsRead(Long receiverId) {
        return lambdaUpdate()
                .eq(Message::getReceiverId, receiverId)
                .eq(Message::getStatus, 0)
                .set(Message::getStatus, 1)
                .set(Message::getReadTime, LocalDateTime.now())
                .update();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean broadcastMessage(String title, String content, Integer type) {
        // 获取所有用户
        List<User> users = userMapper.selectList(null);
        if (CollUtil.isEmpty(users)) {
            return false;
        }

        List<Long> userIds = users.stream().map(User::getId).toList();
        return batchSendMessage(userIds, title, content, type);
    }
} 